@echo off
chcp 65001 >nul
title 下载 Cloudflare Tunnel
color 0B

echo.
echo ========================================================
echo           自动下载 Cloudflare Tunnel
echo ========================================================
echo.

echo 🔍 检查是否已有 cloudflared.exe...
if exist "cloudflared.exe" (
    echo ✅ cloudflared.exe 已存在
    echo 📝 版本信息:
    cloudflared.exe version
    echo.
    echo 💡 如需更新，请删除现有文件后重新运行此脚本
    pause
    exit /b 0
)

echo 📥 正在下载 Cloudflare Tunnel...
echo 🌐 下载地址: GitHub Releases

powershell -Command "& {
    Write-Host '🔍 获取最新版本信息...' -ForegroundColor Green
    try {
        $response = Invoke-RestMethod -Uri 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest' -UseBasicParsing
        $version = $response.tag_name
        Write-Host '📦 最新版本:' $version -ForegroundColor Yellow
        
        $downloadUrl = 'https://github.com/cloudflare/cloudflared/releases/download/' + $version + '/cloudflared-windows-amd64.exe'
        Write-Host '📥 下载链接:' $downloadUrl -ForegroundColor Cyan
        
        Write-Host '⏬ 开始下载...' -ForegroundColor Green
        Invoke-WebRequest -Uri $downloadUrl -OutFile 'cloudflared.exe' -UseBasicParsing
        
        Write-Host '✅ 下载完成!' -ForegroundColor Green
        Write-Host '📁 文件位置: cloudflared.exe' -ForegroundColor Yellow
    }
    catch {
        Write-Host '❌ 下载失败:' $_.Exception.Message -ForegroundColor Red
        Write-Host '💡 请手动下载: https://github.com/cloudflare/cloudflared/releases/latest' -ForegroundColor Yellow
        exit 1
    }
}"

if %errorlevel% neq 0 (
    echo.
    echo ❌ 自动下载失败
    echo 💡 请手动下载：
    echo    1. 访问: https://github.com/cloudflare/cloudflared/releases/latest
    echo    2. 下载: cloudflared-windows-amd64.exe
    echo    3. 重命名为: cloudflared.exe
    echo    4. 放到项目根目录
    pause
    exit /b 1
)

echo.
echo ✅ 验证下载结果...
if exist "cloudflared.exe" (
    echo ✅ cloudflared.exe 下载成功
    echo 📝 版本信息:
    cloudflared.exe version
    echo.
    echo 🎉 现在可以使用 Cloudflare Tunnel 了！
    echo 💡 运行命令: start_cloudflare_tunnel.bat
) else (
    echo ❌ 文件不存在，下载可能失败
)

echo.
pause 